import React from 'react';
import {Dimensions, ScrollView, StyleSheet, View} from 'react-native';
import UltimateListView from '../components/UltimateListView/ultimateListView';
import HttpUtil from '../network/HttpUtil';
import PropTypes from 'prop-types';

const WIN_WIDTH = Dimensions.get('window').width;

//闪屏页
class ListPage extends React.PureComponent {

        static propTypes = {
                url: PropTypes.string,
                params: PropTypes.object,
                dataKey: PropTypes.string,
                renderItem: PropTypes.func,
                separatorHeight: PropTypes.number,
                separatorColor: PropTypes.string,
                separator: PropTypes.object,
                separatorStyle: PropTypes.object,
                mock: PropTypes.bool,
                pageKey: PropTypes.string,
                pageSizeKey: PropTypes.string,
                /**
                 * list本身的ListHeaderComponent
                 */
                header: PropTypes.func,
                footer: PropTypes.func,
                contentContainerStyle: PropTypes.object,
                stickyHeader: PropTypes.bool,
                /**
                 * 当前page的顶部header
                 */
                pageHeader: PropTypes.func,
                pageFooter: PropTypes.func,
                startPage: PropTypes.number,
                listFromData: PropTypes.func,
                requestMethod: PropTypes.string,
                index: PropTypes.number,
                emptyViewText: PropTypes.string,
                numColumns: PropTypes.number,
                pagination: PropTypes.bool,
                /**
                 * 是否显示list
                 */
                hideList: PropTypes.func,
                /**
                 * 不显示list时的替代view
                 */
                listReplacementComponent: PropTypes.func,
                paramsFunc: PropTypes.func,
                refreshFunc: PropTypes.func,
                refreshableMode: PropTypes.string,
                dataSource: PropTypes.array,
        };

        static defaultProps = {
                startPage: 1,
                pageSizeKey: 'limit',
                params: {},
                numColumns: 1,
                pagination: true,
                waterfall: false,
                refreshableMode: 'advanced',
                requestMethod: 'post',
                paramsFunc: null,
                refreshFunc: null,
        };

        constructor(props) {
                super(props);
                this.data = [];
                this.currentPage = 1;
                this.state = {isRefreshing: false, noMoreData: false};
        }

        refresh = () => {
                if (this.props.refreshFunc) {
                        this.props.refreshFunc(this.props.index);
                }
                this.listView.refresh();
        };

        onFetch = async (page = 1, startFetch, abortFetch) => {
                try {
                        if (this.props.refreshFunc && page === 1) {
                                this.props.refreshFunc(this.props.index);
                        }
                        let params = this.props.params;
                        if (this.props.paramsFunc) {
                                params = {...params, ...this.props.paramsFunc(this.props.index, page)};
                        }
                        let pageSize = params[this.props.pageSizeKey] || 10;
                        if (this.props.mock) {
                                requestAnimationFrame(() => {
                                        startFetch([1, 2, 3, 4, 5, 6, 7], pageSize);
                                });
                        } else {
                                if (this.props.dataSource && !this.props.pagination) {
                                        requestAnimationFrame(() => {
                                                startFetch(this.props.dataSource, 1000000);
                                        });
                                } else {
                                        const pageKey = this.props.pageKey || 'curpage';
                                        const {data} = await HttpUtil.do(this.props.requestMethod, this.props.url, {
                                                ...params,
                                                [pageKey]: page,
                                        });
                                        let list = null;
                                        if (this.props.listFromData) {
                                                list = await this.props.listFromData(data, this.props.index, (value) => {
                                                        startFetch(value, pageSize);
                                                });
                                                if (list) {
                                                        startFetch(list, pageSize);
                                                }
                                        } else {
                                                list = this.dataForKeyPath(data, this.props.dataKey);
                                                startFetch(list, pageSize);
                                        }
                                }
                        }
                } catch (err) {
                        abortFetch(err.message); //manually stop the refresh or pagination if it encounters network error
                        console.log(err);
                }
        };

        dataForKeyPath(data, keyPath) {
          if (!data) {
            return [];
            }
                if (!keyPath || keyPath.length === 0) {
                        return data;
                }
                if (keyPath.indexOf('.') >= 0) {
                        const path = keyPath.split('.');
                        let temp = data;
                        for (let i = 0; i < path.length; ++i) {
                                temp = temp[path[i]];
                        }
                        return temp || [];
                } else {
                        return data[keyPath] || [];
                }
        }

        renderSeparator = () => {
                if (this.props.separator) {
                        return this.props.separator;
                }
                return <View style={{
                        height: this.props.separatorHeight || 0.5,
                        backgroundColor: this.props.separatorColor || '#eeeeee',
                        ...this.props.separatorStyle,
                }}/>;
        };

        renderItem = ({item, index}) => {
                if (this.props.renderItem) {
                        return this.props.renderItem({item, index, list: this, key: this.props.index});
                }
                return <View style={{height: 44}}><Text>a</Text></View>;
        };

        deleteRow(item) {
          this.listView && this.listView.deleteRow(item);
        }

        prependRow(item) {
          this.listView && this.listView.prependRow(item);
        }

        render() {
                const viewStyle = {flex: 1, alignItems: 'stretch', backgroundColor: 'transparent', overflow: 'hidden'};
                return (<View
                    style={[viewStyle, this.props.style]}
                >
                        {this.props.pageHeader && this.props.pageHeader(this.props.index, this)}
                        {this.renderList()}
                        {this.props.pageFooter && this.props.pageFooter(this.props.index, this)}
                </View>)
                    ;
        }

        renderList() {
                if (this.props.hideList && this.props.hideList(this.props.index)) {
                        if (this.props.header) {
                                return <ScrollView style={{flex: 1}} contentContainerStyle={{alignItems: 'stretch'}}>
                                        {this.props.header && this.props.header()}
                                        {this.props.listReplacementComponent && this.props.listReplacementComponent(this.props.index, this)}
                                </ScrollView>;
                        } else {
                                return this.props.listReplacementComponent && this.props.listReplacementComponent(this.props.index, this);
                        }
                } else {
                        return this.renderListPage();
                }
        }

        getData() {
                return this.listView.getRows();
        }

        renderListPage = () => {
                return <UltimateListView
                    {...this.props}
                    ref={list => this.listView = list}
                    onFetch={this.onFetch}
                    renderItem={this.renderItem}
                    keyExtractor={(item, index) => {
                            if (this.props.keyExtractor) {
                                    return this.props.keyExtractor({item, index});
                            } else {
                                    return `${index}`;
                            }
                    }}
                    separator={this.renderSeparator}
                    stickyHeaderIndex={this.props.stickyHeader ? 0 : -1}
                />;
        };

}

const styles = StyleSheet.create({});
export default ListPage;

